package com.example.demo.service.member;


import com.example.demo.entity.member.User;
import com.example.demo.repository.SysUser.SysUserRepository;
import com.example.demo.repository.member.UserRepository;
import com.example.demo.service.MailService;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;

/**
 * @author longzhonghua
 * @data 2018/11/04 22:30
 */

@Service
public class UserServiceImpl implements UserService {
    @Resource
    private PasswordEncoder passwordEncoder;

    @Autowired
    private UserRepository userRepository;
    @Resource
    private SysUserRepository adminRepository;
    @Resource
    private RabbitTemplate rabbitTemplate;

    @Resource
    private StringRedisTemplate stringRedisTemplate;

    @Override
    public void save(User user) {
        userRepository.save(user);
    }

    @Override
    public Page<User> PageByUser(Integer page, Integer size) {
        Pageable pageable = new PageRequest(page,size, Sort.Direction.ASC, "id");
        return userRepository.findAll(pageable);
    }

    @Override
    public User findByUserName(String username) {
        return userRepository.findByName(username);
    }

    @Override
    public String login(User user) {
        String account = user.getAccount();
        User returnUser = null;
       /* if(userRepository.findByEmail(account)!=null
            || userRepository.findByMobile(account)!=null
            || userRepository.findByName(account)!=null
            || adminRepository.findByName(account)!=null) {
            return "用户已存在";
        }*/
        //判断是邮箱还是手机号的正则表达式
        String email = "^\\w+([-+.]\\w+)*@\\w+([-.]\\w+)*\\.\\w+([-.]\\w+)*$";
        String phone = "^[1][34578]\\d{9}$";
        if(account.matches(email)) {
            returnUser = userRepository.findByEmail(account);
        } else if(account.matches(phone)) {
            returnUser = userRepository.findByMobile(account);
        } else {
            returnUser = userRepository.findByName(account);
        }
        if(returnUser == null) {
            return "用户不存在";
        } else if(!passwordEncoder.matches(user.getPassword(),returnUser.getPassword())) {
            return "密码不正确";
        } else if(!returnUser.isEnabled()) {
            return "用户未激活";
        }
        return "success";
    }

    @Override
    public String regByPhone(User user, String verificationCode) {
        if(exists(user.getMobile())) return "用户已存在";
        ValueOperations<String,String> ops = stringRedisTemplate.opsForValue();
        String code = ops.get(user.getMobile());
        if(StringUtils.isEmpty(code)
            || !code.equals(verificationCode)) {
            return "验证码错误";
        }
        user.setPassword(passwordEncoder.encode(user.getPassword()));
        userRepository.save(user);
        return "success";
    }

    public String regByEmail(User user) {
        if(exists(user.getEmail())) return "用户已存在";
        //mq发送激活邮件
//        mailService.sendActiveEmail(user.getEmail());
        //往mq队列reg_email中发送一条消息，内容是注册的邮箱地址例如aaa@aa.com
        rabbitTemplate.convertAndSend("reg_email",user.getEmail());
        //保存到数据库
        user.setPassword(passwordEncoder.encode(user.getPassword()));
        userRepository.save(user);
        return "success";
    }

    @Override
    public String regByName(User user) {
        if(exists(user.getName())) return "用户已存在";
        user.setPassword(passwordEncoder.encode(user.getPassword()));
        userRepository.save(user);
        return "success";
    }

    @Override
    public String activeuserEmail(String sid) {
        String email = stringRedisTemplate.opsForValue().get(sid);
        if(StringUtils.isEmpty(email)) {
            return "激活失败";
        }
        //update user set enabled=1 where email=?
        userRepository.setActive(1,email);
        return "激活成功";
    }

    private boolean exists(String account) {
        if(userRepository.findByEmail(account)!=null
                || userRepository.findByMobile(account)!=null
                || userRepository.findByName(account)!=null
                || adminRepository.findByName(account)!=null) {
            return true;
        }
        return false;
    }
}
